package com.nervenets.template.service.impl;

import com.nervenets.general.redis.RedisSyncLocker;
import com.nervenets.general.service.impl.BaseServiceImpl;
import com.nervenets.template.hibernate.dao.DataOfMoneyDao;
import com.nervenets.template.hibernate.domain.data.DataOfMoney;
import com.nervenets.template.service.DataOfMoneyService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class DataOfMoneyServiceImpl extends BaseServiceImpl<DataOfMoney, DataOfMoneyDao> implements DataOfMoneyService {
    @Resource
    private RedisSyncLocker<Void> redisSyncLocker;

    @Override
    public DataOfMoney checkAndGenerateData(long timestamp) {
        DataOfMoney dataOfMoney = dao.findByCreateTime(timestamp);
        if (null == dataOfMoney) {
            dataOfMoney = new DataOfMoney();
            dataOfMoney.setCreateTime(timestamp);
            save(dataOfMoney);
        }
        return dataOfMoney;
    }

    @Override
    public void updateData(long startOfDayTime, long recharge, long human, long withdraw, long refund) throws Exception {
        redisSyncLocker.keyLock("DataOfMoney" + startOfDayTime, () -> {
            DataOfMoney dataOfMoney = checkAndGenerateData(startOfDayTime);
            if (recharge != 0) dataOfMoney.setRecharge(recharge);
            if (human != 0) dataOfMoney.setHuman(human);
            if (withdraw != 0) dataOfMoney.setWithdraw(withdraw);
            if (refund != 0) dataOfMoney.setRefund(refund);
            save(dataOfMoney);
            return null;
        });
    }
}
